<template>
  <div class="qz">
    <div class="head-search">
      <search @onSubmit="onSearch">
        <el-form-item label="角色名称：">
          <el-input clearable placeholder="请输入内容" v-model="info.val" size="small"></el-input>
        </el-form-item>
      </search>
      <el-button class="reset" size="small" icon="el-icon-refresh" @click="handleReset">重置</el-button>
    </div>
    <div class="fun-btn">
      <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="handleAddEdit('add')">新增
      </el-button>
      <el-button type="danger" plain size="small" icon="el-icon-delete" @click="handleDel('batch')">批量删除</el-button>
    </div>

    <section class="list-box">
      <el-table
        :data="tableData.list"
        border
        v-loading="loading"
        height="calc(100vh - 235px)"
        @selection-change="handleSelectionChange"
        ref="table"
        class="table">
        <el-table-column
          type="selection"
          fixed="left"
          align="center"
          width="60">
        </el-table-column>
        <el-table-column
          type="index"
          fixed="left"
          label="序号"
          align="center"
          width="60">
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="roleName"
          label="角色名称"
          width="150">
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="roleCode"
          label="角色代码"
          width="120">
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="isSysRole"
          label="系统角色"
          width="100">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.isSysRole" @change="handleUpdate(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="isEnable"
          label="可用"
          width="100">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.isEnable" @change="handleUpdate(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="orderNo"
          label="角色序号"
          width="150">
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          :formatter="formatDate"
          prop="gmtCreate"
          label="创建日期"
          width="180">
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="remark"
          label="备注"
          width="300">
        </el-table-column>
        <el-table-column
          fixed="right"
          align="center"
          label="操作"
          width="240">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-view" @click="handleAddEdit('see', scope.row)">查看</el-button>
            <el-button type="text" icon="el-icon-edit" @click="handleAddEdit('edit', scope.row)">编辑</el-button>
            <el-dropdown class="" trigger="click" @command="handleCommand($event, scope.row)">
              <span class="el-dropdown-link">
                权限管理<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="分配用户">分配用户</el-dropdown-item>
                <el-dropdown-item command="菜单权限">菜单权限</el-dropdown-item>
                <el-dropdown-item command="数据权限">数据权限</el-dropdown-item>
                <el-dropdown-item command="门类权限">门类权限</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="searchData.pageNo"
        :page-sizes="[20, 40, 60, 80]"
        :page-size="searchData.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="Number(tableData.total)">
      </el-pagination>
    </section>

    <el-drawer
      :title="setDrawer.title"
      :size="setDrawer.size"
      :direction="setDrawer.direction"
      :visible.sync="drawer"
    >
      <assign-users :dataList="dataList"
                    :value="value"
                    @handleSetTransfer="handleSetTransfer"
                    v-if="setDrawer.title === '分配用户'"></assign-users>
      <menu-permissions :treeList="menuTreeList"
                        :checkedArr="checkedMenuTreeArr"
                        :saveLoading="menuSaveLoading"
                        :loading="getLoading"
                        @handleMenuSubmit="handleMenuSubmit"
                        v-if="setDrawer.title === '菜单权限'"></menu-permissions>
      <data-permissions @handleSaveCategory="handleSaveCategory"
                        ref="dataPer"
                        :categoryData="categoryData"
                        :saveTreeLoading="saveTreeLoading"
                        v-if="setDrawer.title === '门类权限'"></data-permissions>

      <mechanism-permissions @handleSubmitSave="handleSubmitSave"
                             ref="dataPer"
                             :orgData="orgData"
                             :categoryData="categoryData"
                             :categoryTree="categoryTree"
                             :saveLoading="saveLoading"
                             :saveTreeLoading="saveTreeLoading"
                             v-if="setDrawer.title === '数据权限'"></mechanism-permissions>

    </el-drawer>

    <el-dialog :title="dialogTitle"
               width="50%"
               top="5vh"
               :destroy-on-close="true"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :visible.sync="dialogAddEdit"
               :before-close="(done)=>{ type = 'add';done()  }">
      <div class="import-content">
        <add-edit :type="type"
                  :editData="editData"
                  @handleSuccess="handleSuccess"></add-edit>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import Search from '../../../../components/search/search'
import AddEdit from '../settingComponents/role/addEdit'
import AssignUsers from '../settingComponents/user/assignUsers'
import MenuPermissions from '../settingComponents/menuPermissions'
import DataPermissions from '../settingComponents/dataPermissions'
import {
  delRole,
  editRole, editRoleMenuSeted,
  getRoleList, getRoleMenuSeted, getUserList, saveRoleCategoryJurisdiction, saveRoleMechanismJurisdiction,
  transferAddUser, transferRemoveUser, transferUserSelected
} from '../../../../api/user/userSet'
import { getMenuJurisdiction } from '../../../../api/menu/menuLeftNav'
import { getRoleJurisdiction } from '../../../../api/dataJurisdiction'
import { getRoleCategoryKeys } from '../../../../api/category/category'
import MechanismPermissions from '../settingComponents/mechanismPermissions'

export default {
  name: 'Role', // 角色管理
  components: {
    MechanismPermissions,
    DataPermissions,
    MenuPermissions,
    AssignUsers,
    AddEdit,
    Search
  },
  data () {
    return {
      drawer: false, //
      setDrawer: {
        title: '',
        size: '',
        direction: 'ltr'
      },
      value: [], // 穿梭框右边数据
      dataList: [], // 穿梭框数据
      page: {
        pageNo: 1,
        pageSize: 1000
      },
      dialogAddEdit: false,
      type: 'add',
      dialogTitle: '',
      editData: {},
      info: {
        val: ''
      },
      searchData: {
        pageNo: 1,
        pageSize: 20
      },
      tableSelected: [],
      loading: true,
      tableData: [],
      menuTreeList: [], // 菜单权限树
      checkedMenuTreeArr: [], // 菜单权限树选中节点
      menuSaveLoading: false, // 菜单权限树提交loading
      orgData: {}, // 获取用户机构权限
      categoryData: [], // 获取用户门类权限
      categoryTree: [], // 获取用户门类权限树
      saveLoading: false,
      saveTreeLoading: false,
      getLoading: false
    }
  },
  mounted () {
    this.getList()
  },
  methods: {
    getList () {
      this.loading = true
      getRoleList(this.searchData).then((res) => {
        this.tableData = res.data.data
        this.loading = false
      }).catch(() => {
        this.tableData = {
          list: [],
          total: 0
        }
        this.loading = false
      })
    },
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      this.searchData.pageSize = val
      this.getList()
    },
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`)
      this.searchData.pageNo = val
      this.getList()
    },
    onSearch () {
      // 搜索
      this.searchData.pageSize = 20
      this.searchData.pageNo = 1
      if (this.info.val) {
        this.searchData.params = [{
          op: 'like',
          name: 'role_name',
          value: this.info.val
        }]
      } else {
        delete this.searchData.params
      }
      this.getList()
    },
    handleUpdate (row) {
      // 开关 系统角色、可用
      editRole(row).then(() => {
        this.$message.success('操作成功！')
      })
    },
    handleReset () {
      // 重置
      this.info.val = ''
    },
    handleSelectionChange (selection) {
      // 勾选表格行
      this.tableSelected = selection
    },
    handleAddEdit (type, row) {
      const title = {
        add: '新增',
        edit: '修改',
        see: '查看'
      }
      this.type = type
      this.dialogTitle = title[type]
      this.dialogAddEdit = true
      this.dialogAddEdit = true
      this.editData = row || {}
    },
    handleSuccess () {
      // 新增成功
      this.dialogAddEdit = false
      this.getList()
    },
    handleDel () {
      // 批量删除
      if (this.tableSelected.length > 0) {
        this.$confirm('此操作将永久删除选中的用户信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const ids = []
          this.tableSelected.map((item) => {
            ids.push(item.id)
          })
          delRole(ids).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getList()
          })
        }).catch(() => {
        })
      } else {
        this.$message.error('请最少选择一条信息删除！')
      }
    },
    handleCommand (command, row) {
      this.roleId = row.id
      if (command === '分配用户') {
        this.value = []
        this.dataList = []
        getUserList({
          pageNo: 1,
          pageSize: 100
        }).then(res => {
          this.dataList = res.data.data.list
          transferUserSelected(this.roleId, this.page).then(resd => {
            resd.data.data.list.map(item => {
              this.value.push(item.id)
            })
          })
        })
      } else if (command === '菜单权限') {
        this.getLoading = true
        getMenuJurisdiction(this.page).then(res => {
          getRoleMenuSeted(this.roleId, []).then(resd => {
            this.checkedMenuTreeArr = resd.data.data.menuIds
            const arr = res.data.data.list || []
            this.menuTreeList = []
            arr.map(item => {
              if (item !== 'null') {
                this.menuTreeList.push(item)
              }
            })
            this.getLoading = false
          }).catch(() => {
            this.getLoading = false
          })
        })
      } else if (command === '门类权限') {
        this.categoryTree = []
        getRoleCategoryKeys(this.roleId).then(res => {
          const arr = res.data.data || []
          this.categoryData = []
          arr.map(item => {
            if (item !== 'null') {
              this.categoryData.push(item)
            }
          })
        })
      } else if (command === '数据权限') {
        getRoleJurisdiction(this.roleId).then(res => {
          this.orgData = res.data.data || {}
        })
      }
      this.handleDrawer(command)
    },
    handleSetTransfer (val) {
      // 设置穿梭框值
      if (val.direction === 'right') {
        transferAddUser(this.roleId, val.ids).then(() => {
          this.$message.success('设置成功')
        })
      } else if (val.direction === 'left') {
        transferRemoveUser(this.roleId, val.ids).then(() => {
          this.$message.success('设置成功')
        })
      }
    },
    handleMenuSubmit (keys) {
      // 菜单权限设置提交
      this.menuSaveLoading = true
      editRoleMenuSeted(this.roleId, { ids: keys }).then(res => {
        this.menuSaveLoading = false
        this.drawer = false
        this.$message.success('设置成功！')
      }).catch(() => {
        this.menuSaveLoading = false
      })
    },
    handleSubmitSave (val) {
      // 机构权限范围设置
      if (this.orgData.id) {
        val.id = this.orgData.id
      }
      val.idData = this.roleId
      val.dataType = 'role'
      this.saveLoading = true
      saveRoleMechanismJurisdiction(val).then(res => {
        this.$message.success('设置成功')
        this.saveLoading = false
        this.drawer = false
      }).catch(() => {
        this.saveLoading = false
      })
    },
    handleSaveCategory (val) {
      // 门类数据权限范围设置
      val.idData = this.roleId
      this.saveTreeLoading = true
      saveRoleCategoryJurisdiction(val).then(res => {
        this.$message.success('设置成功')
        this.saveTreeLoading = false
        this.drawer = false
      }).catch(() => {
        this.saveTreeLoading = false
      })
    },
    handleDrawer (type) {
      const arr = [{
        title: '分配用户',
        size: '60%',
        direction: 'rtl'
      }, {
        title: '菜单权限',
        size: '80%',
        direction: 'rtl'
      }, {
        title: '数据权限',
        size: '500px',
        direction: 'rtl'
      }, {
        title: '门类权限',
        size: '300px',
        direction: 'rtl'
      }]
      this.drawer = true
      arr.map(item => {
        if (item.title === type) {
          this.setDrawer = item
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>

  .head-search {
    ::v-deep .search-btn {
      margin-top: 0;
    }
  }

  .reset {
    margin-top: 5px;
  }

  .menu-permissions {
    display: flex;
    justify-content: flex-start;
    height: 100%;
    background: #e9e9e9;
    padding: 15px 10px;
  }

  .el-dropdown-link {
    color: #409EFF;
    margin-left: 10px;
    cursor: pointer;
  }
</style>
